package com.springboot.blog.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.springboot.blog.dto.LayPage;
import com.springboot.blog.dto.LayResponse;
import com.springboot.blog.entity.Role;
import com.springboot.blog.entity.User;
import com.springboot.blog.entity.UserRole;
import com.springboot.blog.interfaces.ToolInterface;
import com.springboot.blog.service.IRoleService;
import com.springboot.blog.service.IUserRoleService;
import com.springboot.blog.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
class AdminUserController {
    @Autowired
    IUserService userService;
    @Autowired
    IRoleService roleService;
    @Autowired
    IUserRoleService userRoleService;
    String PATH = "admin/user/";

    @RequiresPermissions("user:list")
    @GetMapping(value = {"/admin/user/index", "/admin/user"})
    public String index() {
        return PATH + "index";
    }

    @RequiresPermissions("user:list")
    @GetMapping(value = {"/admin/user/tree"})
    @ResponseBody
    public LayResponse tree(Integer page, Integer limit) {
        page = page == null ? 1 : page;
        limit = limit == null ? 10 : limit;
        LayPage<User> pageUser = new LayPage<>(page, limit);
        userService.page(pageUser);
        return pageUser.getLayResponse();
    }

    @RequiresPermissions("user:delete")
    @PostMapping(value = {"/admin/user/delete"})
    @ResponseBody
    public LayResponse delete(String id) {
        boolean result = userService.removeById(id);
        LayResponse layResponse = new LayResponse();
        if (result) {
            return layResponse.success();
        }
        return layResponse.error();
    }

    @RequiresPermissions("user:delete")
    @PostMapping(value = {"/admin/user/deleteAll"})
    @ResponseBody
    public LayResponse deleteAll(@RequestParam("ids[]") List<Integer> ids) {
        boolean result = userService.removeByIds(ids);
        LayResponse layResponse = new LayResponse();
        if (result) {
            return layResponse.success();
        }
        return layResponse.error();
    }

    @RequiresPermissions("user:add")
    @GetMapping(value = {"/admin/user/add"})
    public String add(Model model) {
        List<Role> list = roleService.list();
        model.addAttribute("list", list);
        return PATH + "add";
    }

    @RequiresPermissions("user:add")
    @PostMapping(value = {"/admin/user/add"})
    @ResponseBody
    public LayResponse add(@Validated(ToolInterface.insert.class)User user, @RequestParam("roles[]") int[] roles) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userService.save(user);
        List<UserRole> rs = new ArrayList<>();
        for (int roleId : roles) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            rs.add(userRole);
        }
        userRoleService.saveBatch(rs);
        return new LayResponse().success();
    }

    @RequiresPermissions("user:edit")
    @GetMapping(value = {"/admin/user/edit"})
    public String edit(@RequestParam String id, Model model) {
        User data = userService.getById(id);
        List<UserRole> list1 = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, id));
        List<Map<String, Object>> list = roleService.listMaps();
        if (list1 != null) {
            List<Integer> list_all = new ArrayList<>();
            for (UserRole ur : list1) {
                list_all.add(ur.getRoleId());
            }
            for (Map<String, Object> map : list) {
                Long id1 = (Long) map.get("id");
                if (list_all.contains(id1.intValue())) {
                    map.put("checked", "true");
                } else {
                    map.put("checked", "false");
                }
            }
        }
        model.addAttribute("list", list);
        model.addAttribute("data", data);
        return PATH + "edit";
    }

    @RequiresPermissions("user:edit")
    @PostMapping(value = {"/admin/user/edit"})
    @ResponseBody
    public LayResponse edit(@Validated(ToolInterface.update.class) User user, @RequestParam("roles[]") List<Integer> rolesId) {
        userService.updateById(user);
        userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()));
        for (int roleId : rolesId) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            userRoleService.save(userRole);
        }
        return new LayResponse().success();
    }

    @RequiresPermissions("user:edit")
    @PostMapping(value = {"/admin/user/editPwd"})
    @ResponseBody
    public LayResponse editPwd(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userService.updateById(user);
        return new LayResponse().success();
    }

    @RequiresPermissions("user:edit")
    @PostMapping(value = {"/admin/user/ajax"})
    @ResponseBody
    public LayResponse ajax(User user) {
        boolean b = userService.updateById(user);
        LayResponse layResponse = new LayResponse();
        if (b) {
            return layResponse.success();
        }
        return layResponse.error();
    }
}
